//
//  SNBpDetailVc.m
//  project
//
//  Created by 黄建华 on 2017/12/12.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNBpDetailVc.h"
#import "SNBpChartView.h"
#import "SNBpDetailTableViewCell.h"

#define LEFTWIDTH    30.0
//#define SNHEARTBIG   [UIColor colorFromHex:0xf41628]
//#define SNHEARTSMALL [UIColor colorFromHex:0xf99938]
#define SNHEARTBIG   [UIColor colorFromHex:0xFF2D55]
#define SNHEARTSMALL [UIColor colorFromHex:0x68E7FF]

@interface SNBpDetailVc ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UIView         *headView;     //下拉视图
@property (nonatomic, strong) UITableView    *tableView;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) SNBpChartView  *ChartView;
@property (nonatomic, assign) SelectDateType type;
@property (nonatomic, strong) UIView         *labelView;

@end

@implementation SNBpDetailVc

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initTabelView];
}

- (void)initTabelView {
    _tableView                = [[UITableView alloc]initWithFrame:CGRectMake(0, 70+FitSimpleIpx(0, 20), HHHWIDTH, HHHHEIGHT - 70 -FitSimpleIpx(0, 20)) style:UITableViewStylePlain];
    _tableView.delegate       = self;
    _tableView.dataSource     = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    _headView                  = [[UIView alloc] init];
    _headView.frame            = SNFRAME(0, 0, HHHWIDTH, _tableView.height *0.60);
    _tableView.tableHeaderView = _headView;
    
    _ChartView = [[SNBpChartView alloc] initWithFrame:SNFRAME(LEFTWIDTH, 0, HHHWIDTH - LEFTWIDTH, _headView.height *0.6)];
    [_headView addSubview:_ChartView];
    
    [self loadLabelValue];
    
    UIView *bgView = [[UIView alloc] initWithFrame:SNFRAME(0, _labelView.bottom, screenWidth, 100)];
    [self.headView addSubview:bgView];
    bgView.backgroundColor = UIColorHEX(0xF2F4F5);
    
    UIView *bgView2 = [[UIView alloc] initWithFrame:SNFRAME(15,15, screenWidth-30, 70)];
    [bgView addSubview:bgView2];
    bgView2.layer.cornerRadius = 6;
    bgView2.backgroundColor = UIColorHEX(0xffffff);
    
    UIImageView *sleepImg = [[UIImageView alloc] init];
    sleepImg.frame = SNFRAME(15, 16, 38, 38);
    sleepImg.image = [UIImage imageNamed:@"血压222"];
    [bgView2 addSubview:sleepImg];
    
    UILabel *sleepTypeLabel = [[UILabel alloc] init];
    sleepTypeLabel.textAlignment = NSTextAlignmentLeft;
    sleepTypeLabel.frame         = SNFRAME(66, 25, 120, 20);
    sleepTypeLabel.textColor     = SNCOLORBLACK;
    sleepTypeLabel.text          = SN_Text(@"血压详情");
    sleepTypeLabel.font          = SNFONTMEDIUM(18);
    sleepTypeLabel.adjustsFontSizeToFitWidth = YES;
    [bgView2 addSubview:sleepTypeLabel];
    
    UIView *red = [[SNShadowView alloc] init];
    red.frame               = SNFRAME(bgView2.width/2, 30, 10, 10);
    red.backgroundColor     = SNHEARTBIG;
    red.layer.masksToBounds = YES;
    red.layer.cornerRadius  = red.width / 2.0;
    [bgView2 addSubview:red];
    
    UILabel *redLabel = [[UILabel alloc] init];
    redLabel.textAlignment = NSTextAlignmentLeft;
    redLabel.frame         = SNFRAME(red.center.x + 10, red.center.y-15, 65, 30);
    redLabel.textColor     = UIColorHEX(0x424242);
    redLabel.text          = SN_Text(@"舒张压异常");
    redLabel.numberOfLines = 0;
    redLabel.font          = SNFONTREGULAR(10);
    [bgView2 addSubview:redLabel];
    
    UIView *low = [[SNShadowView alloc] init];
    low.frame               = SNFRAME(redLabel.right +10, 30, 10, 10);
    low.backgroundColor     = SNHEARTSMALL;
    low.layer.masksToBounds = YES;
    low.layer.cornerRadius  = low.width / 2.0;
    [bgView2 addSubview:low];
    
    UILabel *lowLabel = [[UILabel alloc] init];
    lowLabel.textAlignment = NSTextAlignmentLeft;
    lowLabel.frame         = SNFRAME(low.center.x + 10, low.center.y-15, 65, 30);
    lowLabel.textColor     = UIColorHEX(0x424242);
    lowLabel.text          = SN_Text(@"收缩压异常");
    lowLabel.font          = SNFONTREGULAR(10);
    lowLabel.numberOfLines = 0;
    [bgView2 addSubview:lowLabel];
    
    [self selectType:SelectDateDay];
}

- (void)loadLabelValue {
    _labelView       = [[UIView alloc] init];
    _labelView.frame = SNFRAME(0, _headView.height *0.6, HHHWIDTH, _headView.height *0.2);
    [_headView addSubview:_labelView];
    
    NSArray *arrayValue = [NSArray arrayWithObjects:@"78 mmHg", @"125 mmHg", nil];
    for (int i = 0; i < 2; i++) {
        UILabel *unitLabel = [[UILabel alloc] init];
        unitLabel.textAlignment = NSTextAlignmentCenter;
        unitLabel.text          = arrayValue[i];
        unitLabel.textColor     = SNCOLORBLACK;
        unitLabel.font          = SNFONT(17.0);
        unitLabel.tag           = 100 +i;
        if (i == 0) {
            unitLabel.frame = SNFRAME(self.view.center.x - HHHWIDTH /2 + 3, 10, HHHWIDTH /2, 20);
        } else {
            unitLabel.frame = SNFRAME(self.view.center.x + 3, 10, HHHWIDTH /2, 20);
        }
        [_labelView addSubview:unitLabel];
        [unitLabel setAttributedText:[SN_PublicClass label1With:unitLabel.text withFontsize:10.0 withChangeText1:@"mmHg" withChangeText2:@"mmHg"]];
    }
    
    NSArray *arrayString = [NSArray arrayWithObjects:SN_Text(@"平均舒张压"), SN_Text(@"平均收缩压"), nil];
    for (int i = 0; i < 2; i++) {
        UILabel *unitLabel = [[UILabel alloc] init];
        unitLabel.textAlignment = NSTextAlignmentCenter;
        unitLabel.text          = arrayString[i];
        unitLabel.textColor     = SNCOLORGRAY;
        unitLabel.font          = SNSFONT(13.0);
        if (i == 0) {
            unitLabel.frame = SNFRAME(self.view.center.x - HHHWIDTH /2, 40, HHHWIDTH /2, 20);
        } else {
            unitLabel.frame = SNFRAME(self.view.center.x, 40, HHHWIDTH /2, 20);
        }
        [_labelView addSubview:unitLabel];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _modelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return (_tableView.height *0.35)/7.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"SNBpDetailTableViewCell";
    
    SNBpDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (nil == cell) {
        cell = [[SNBpDetailTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    
    [cell updateCellWithData:_modelArray[indexPath.row]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)selectType:(SelectDateType)type {
    //    NSLog(@"周月年选择了>>>>>>%d",type);
    _type = type;
    BpModel        *model = [BpModel getBpModelFromDBWith:SN_PublicClass.selectDate];
    NSMutableArray *array = [NSMutableArray array];
    _modelArray = [NSMutableArray array];
    if (type == SelectDateDay) {
        //1
        for (int i = 0; i < 24 *4; i++) {
            int sbpTotal = 0;
            int dbpTotal = 0;
            int count    = 0;
            int sbp      = 0;
            int dbp      = 0;
            for (int k = 0; k < model.bpSuArray.count; k++) {
                bpSubModel *bpmodel = [model.bpSuArray objectAtIndex:k];
                
                if (bpmodel.count == i) {
                    sbpTotal += bpmodel.SBPValue;
                    dbpTotal += bpmodel.DBPValue;
                    count++;
                }
            }
            sbp = 1.0 *sbpTotal / count;
            dbp = 1.0 *dbpTotal / count;
            
            if (sbp > 0) {
                int max = 0;
                int min = 0;
                if (sbp > dbp) {
                    max = sbp;
                    min = dbp;
                }
                else
                {
                    max = dbp;
                    min = sbp;
                }
                
                NSDictionary *dic = @{@"SBP":StrByInt(min), @"DBP":StrByInt(max), @"SPACE":StrByInt(max - min)};
                [array addObject:dic];
                
                
            } else {
                NSDictionary *dic = @{@"SBP":StrByInt(0), @"DBP":StrByInt(0), @"SPACE":StrByInt(0)};
                [array addObject:dic];
            }
        }
        //2
        for (int k = 0; k < model.bpSuArray.count; k++) {
            bpSubModel     *bpmodel = [model.bpSuArray objectAtIndex:k];
            NSMutableArray *arr     = [[NSMutableArray alloc] init];
            NSString       *time    = [bpmodel.updateTime componentsSeparatedByString:@" "][1];
            time =  [NSString subString:time withToIndex:5];
            NSString *value1 = StrByInt(bpmodel.SBPValue);
            NSString *value2 = StrByInt(bpmodel.DBPValue);
            [arr addObject:time];
            int max = 0;
            int min = 0;
            if (value1.intValue > value2.intValue) {
                max = value1.intValue;
                min = value2.intValue;
            }
            else
            {
                max = value2.intValue;
                min = value1.intValue;
            }
            
            [arr addObject:StrByInt(min)];
            [arr addObject:StrByInt(max)];
            [_modelArray addObject:arr];
        }
        _modelArray = (NSMutableArray *)[[_modelArray reverseObjectEnumerator] allObjects];
    } else {
        if (type == SelectDateWeek) {
            NSArray *weekArray = [NSArray arrayWithObjects:SN_Text(@"周日"), SN_Text(@"周一"), SN_Text(@"周二"), SN_Text(@"周三"), SN_Text(@"周四"), SN_Text(@"周五"), SN_Text(@"周六"), nil];
            for (int i = 0; i < 7; i++) {
                NSDate   *first       = [SN_PublicClass getMonthBeginAndEndWith:SN_PublicClass.selectDate withType:1];
                NSDate   *Date        = [first dateAfterDay:i];
                NSString *firstString = [Date dateToDayString];
                NSString *ssssbp      = [NSString stringWithFormat:@"SELECT SBPAve FROM BpModel WHERE dateString ='%@' and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
                NSString *sbpValue    = [[BpModel getUsingLKDBHelper]executeScalarWithSQL:ssssbp arguments:nil];
                
                NSString *sssdbp   = [NSString stringWithFormat:@"SELECT DBPAve FROM BpModel WHERE dateString ='%@' and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
                NSString *dbpValue = [[BpModel getUsingLKDBHelper]executeScalarWithSQL:sssdbp arguments:nil];
                
                NSMutableArray *arr = [[NSMutableArray alloc] init];
                [arr addObject:weekArray[i]];
                int sbp = sbpValue.intValue;
                int dbp = dbpValue.intValue;
                int max = 0;
                int min = 0;
                if (sbp > dbp) {
                    max = sbp;
                    min = dbp;
                }
                else
                {
                    max = dbp;
                    min = sbp;
                }
                [arr addObject:StrByInt(min)];
                [arr addObject:StrByInt(max)];
                if (sbp>0&&dbp>0) {
                     [_modelArray addObject:arr];
                }
                NSDictionary *dic = @{@"SBP":StrByInt(min), @"DBP":StrByInt(max), @"SPACE":StrByInt(max - min)};
                [array addObject:dic];
            }
        }
        if (type == SelectDateMonth) {
            NSInteger monthCount = SN_PublicClass.selectDate.daysInMonth;
            for (int i = 0; i < monthCount; i++) {
                NSDate   *first       = [SN_PublicClass getMonthBeginAndEndWith:SN_PublicClass.selectDate withType:2];
                NSDate   *Date        = [first dateAfterDay:i];
                NSString *firstString = [Date dateToDayString];
                NSString *ssssbp      = [NSString stringWithFormat:@"SELECT SBPAve FROM BpModel WHERE dateString ='%@' and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
                NSString *sbpValue    = [[BpModel getUsingLKDBHelper]executeScalarWithSQL:ssssbp arguments:nil];
                
                NSString *sssdbp   = [NSString stringWithFormat:@"SELECT DBPAve FROM BpModel WHERE dateString ='%@' and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
                NSString *dbpValue = [[BpModel getUsingLKDBHelper]executeScalarWithSQL:sssdbp arguments:nil];
                
                NSMutableArray *arr = [[NSMutableArray alloc] init];
                [arr addObject:firstString];
                int sbp = sbpValue.intValue;
                int dbp = dbpValue.intValue;
                int max = 0;
                int min = 0;
                if (sbp > dbp) {
                    max = sbp;
                    min = dbp;
                }
                else
                {
                    max = dbp;
                    min = sbp;
                }
                [arr addObject:StrByInt(min)];
                [arr addObject:StrByInt(max)];
                
                if (sbp && dbp) {
                    [_modelArray addObject:arr];
                }
                 NSDictionary *dic = @{@"SBP":StrByInt(min), @"DBP":StrByInt(max), @"SPACE":StrByInt(max - min)};
                [array addObject:dic];
            }
        }
    }
    [_ChartView UpdateViewWithType:type withArray:array];
    [_tableView reloadData];
    [self updateValueLabel:type];
}

- (void)updateValueLabel:(SelectDateType)type {
    NSString *SBPAve = @"--";
    NSString *DBPAve = @"--";
    
    if (_type == SelectDateDay) {
        BpModel *model = [BpModel getBpModelFromDBWith:SN_PublicClass.selectDate];
        SBPAve = model.SBPAve==0?@"--":[NSString stringWithFormat:@"%d mmHg", model.SBPAve];
        DBPAve = model.DBPAve==0?@"--":[NSString stringWithFormat:@"%d mmHg", model.DBPAve];
    } else {
        NSArray  *time = [SN_PublicClass getBeginDateStringAndEndWith:SN_PublicClass.selectDate withType:_type];
        NSString *max  = [NSString stringWithFormat:@"SELECT AVG(SBPAve) AS OrderTotal FROM BpModel WHERE dateString >='%@' and dateString <='%@' and SBPAve >0 and user_id = '%@'", [time firstObject], [time lastObject], SN_USER.user_id];
        NSString *maxs = [[BpModel getUsingLKDBHelper]executeScalarWithSQL:max arguments:nil];
        SBPAve = maxs.integerValue==0?@"--":[NSString stringWithFormat:@"%d mmHg", maxs.intValue];
        
        NSString *ave  = [NSString stringWithFormat:@"SELECT AVG(DBPAve) AS OrderTotal FROM BpModel WHERE dateString >='%@' and dateString <='%@' and DBPAve >0 and user_id = '%@'", [time firstObject], [time lastObject], SN_USER.user_id];
        NSString *aves = [[BpModel getUsingLKDBHelper]executeScalarWithSQL:ave arguments:nil];
        DBPAve = aves.integerValue==0?@"--":[NSString stringWithFormat:@"%d mmHg", aves.intValue];
    }
    
    int max = 0;
    int min = 0;
    if (SBPAve.intValue > DBPAve.intValue) {
        max = SBPAve.intValue;
        min = DBPAve.intValue;
    }
    else{
        max = DBPAve.intValue;
        min = SBPAve.intValue;
    }
    
    NSArray *array2 = [NSArray arrayWithObjects:StrByInt(min), StrByInt(max), nil];
    if (array2.count > 0) {
        for (UILabel *label in _labelView.subviews) {
            if ([label isKindOfClass:[UILabel class]]) {
                if (label.tag >= 100) {
                    label.text = array2[label.tag - 100];
                }
            }
        }
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

